package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: 40斤
 * @CreateTime: 2024-07-28  19:22
 * @Description: TODO
 * @Version: 1.0
 */
@Service
@Slf4j
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //1.从数据表中查询所有数据
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        //2.将数据转换为map集合
        Map<String, CourseCategoryTreeDto> collect = courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).collect(Collectors.toMap(CourseCategory::getId, Value -> Value, (key1, key2) -> key2));
        //3.创建list集合
        ArrayList<CourseCategoryTreeDto> returnList = new ArrayList<>();
        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item->{
            //与根节点比较，根节点的子节点先放进list中
            if (item.getParentid().equals(id)){
                returnList.add(item);
            }
            //获取该节点的父节点（这里根节点被过滤掉了 所以根节点下一级不会走下面流程）
            CourseCategoryTreeDto parentNode = collect.get(item.getParentid());
            //如果父节点不为空，则将子节点放入父节点的childrenTreeNodes集合中
            if (parentNode!=null){
                //如果父节点的childrenTreeNodes集合为空，则创建集合
                if (parentNode.getChildrenTreeNodes()==null){
                    parentNode.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                //将子节点放入父节点的childrenTreeNodes集合中
                parentNode.getChildrenTreeNodes().add(item);
            }
        });
        return returnList;

    }
}